package com.yc.pre.utils;

import org.apache.commons.lang.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * @ClassName DateUtils
 * @Description 日期处理类
 * @Date 2020/12/10 18:10:23
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
public class DateUtils {

    /**
     * 日期相加减
     * @param time
     *             时间字符串 yyyy-MM-dd HH:mm:ss
     * @param num
     *             加的数，-num就是减去
     * @return
     *             减去相应的数量的年的日期
     */
    public static Date yearAddNum(Date time, Integer num) {
        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //Date date = format.parse(time);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.YEAR, num);
        Date newTime = calendar.getTime();
        return newTime;
    }

    /**
     *
     * @param time
     *           时间
     * @param num
     *           加的数，-num就是减去
     * @return
     *          减去相应的数量的月份的日期
     */
    public static Date monthAddNum(Date time, Integer num){
        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //Date date = format.parse(time);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.MONTH, num);
        Date newTime = calendar.getTime();
        return newTime;
    }

    /**
     *
     * @param time
     *           时间
     * @param num
     *           加的数，-num就是减去
     * @return
     *          减去相应的数量的天的日期
     */
    public static Date dayAddNum(Date time, Integer num){
        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //Date date = format.parse(time);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.DAY_OF_MONTH, num);
        Date newTime = calendar.getTime();
        return newTime;
    }

    /**
     * 获取本月第一天时间
     */
    public static Date getMonthStartDate(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH,1);
        return calendar.getTime();
    }

    /**
     * 获取本月最后一天
     *
     */
    public static Date getMonthEndDate(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return calendar.getTime();
    }
    /**
     * 获取本周的开始时间
     */
    public static Date getBeginWeekDate(){
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
        //周日是1 ，周一是 2 ，周二是 3
        //所以，当周的第一天 = 当前日期 - 距离周一过了几天（周一过了0天，周二过了1天，   周日过了6天）
        // 2 - 周一的（dayofweek：2 ）= 0
        // 2 - 周二的（dayofweek：3 ）= -1
        //                      .
        //                      .
        // 2 - 周日的（dayofweek：1） = 1（这个是不符合的需要我们修改）===》2 - 周日的（dayofweek：1 ==》8 ） = -6
        if (dayofweek == 1) {
            dayofweek += 7;
        }
        cal.add(Calendar.DATE, 2 - dayofweek);
        return cal.getTime();
    }

    /**
     * 本周的结束时间
     * 开始时间 + 6天
     */
    public static Date getEndWeekDate(){
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayofweek == 1) {
            dayofweek += 7;
        }
        cal.add(Calendar.DATE, 8 - dayofweek);//2 - dayofweek + 6
        return cal.getTime();
    }

    public static Integer compareDate(Date date1, Date date2){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDate = sdf.format(date1);
        String secondDate = sdf.format(date2);
        try {
            Date fromDate = sdf.parse(firstDate);
            Date toDate = sdf.parse(secondDate);
            long fromTime = fromDate.getTime();
            long toTime = toDate.getTime();
            int days = (int) ((toTime - fromTime) / (1000 * 60 * 60 * 24));
            return days;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断是否是日期格式
     *
     * @param dateString 时间字符串
     * @param format 格式：yyyy/MM/dd
     * @return
     */
    public static boolean isDate(String dateString, String format) {
        if (StringUtils.isBlank(dateString) || StringUtils.isBlank(format)) {
            return false;
        }
//        if (format.replaceAll("'.+?'", "").indexOf("y") < 0) {
//            format += "/yyyy";
//            DateFormat formatter = new SimpleDateFormat("/yyyy");
//            dateString += formatter.format(new Date());
//        }
        DateFormat formatter = new SimpleDateFormat(format);
        formatter.setLenient(false);
        ParsePosition pos = new ParsePosition(0);
        Date date = formatter.parse(dateString, pos);

        if (date == null || pos.getErrorIndex() > 0) {
            return false;
        }
        if (pos.getIndex() != dateString.length()) {
            return false;
        }
        if (formatter.getCalendar().get(Calendar.YEAR) > 9999) {
            return false;
        }
        return true;
    }

    /**
     * 解析日期等时间
     *
     * @param dateString 时间字符串
     * @param format 格式：yyyy/MM/dd
     * @return
     */
    public static Date parseDate(String dateString, String format) {
        if (StringUtils.isBlank(dateString) || StringUtils.isBlank(format)) {
            return null;
        }
        DateFormat formatter = new SimpleDateFormat(format);
        TimeZone tz = TimeZone.getTimeZone("GMT");
        formatter.setTimeZone(tz);
        formatter.setLenient(true);
        ParsePosition pos = new ParsePosition(0);
        Date date = formatter.parse(dateString, pos);

        if (date == null || pos.getErrorIndex() > 0) {
            return null;
        }
        if (pos.getIndex() != dateString.length()) {
            return null;
        }
        if (formatter.getCalendar().get(Calendar.YEAR) > 9999) {
            return null;
        }
        return date;
    }

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = sdf.parse("2020-10-20");
        Integer integer = compareDate(parse, new Date());
        System.out.println(integer);

        String format = "yyyy/MM/dd";
        System.out.println(isDate("2019/12/01", format));
        System.out.println(isDate("A2020/12/1100", format));
        System.out.println(isDate("2020/A12/1100", format));
        System.out.println(isDate("2020/12/11AA", format));
        System.out.println(isDate("2020/12/32", format));
        System.out.println(isDate("2020/12/", format));
        System.out.println(isDate("2020-12-11", format));
        System.out.println(isDate("2020/12-11", format));
        System.out.println(isDate("2020/13/11", format));
        System.out.println(isDate("12/11", format));
    }

}
